import { useState } from 'react'
import { Form, Input, Button, Card, message } from 'antd'
import { useNavigate } from 'react-router-dom'
const PHONE_REGEX = /^1[3-9]\d{9}$/

function Login() {
    const navigate = useNavigate()
  const [countdown, setCountdown] = useState(0)
  const [form] = Form.useForm()

  // 获取验证码
  const handleGetCode = async () => {
    const phone = form.getFieldValue('phone')
    if (!PHONE_REGEX.test(phone)) {
      message.error('请输入有效的手机号！')
      return
    }
    message.success('验证码已发送到您的手机！')
    setCountdown(60)
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer)
          return 0
        }
        return prev - 1
      })
    }, 1000)
  }

  // 登录提交
  const onFinish = (values: any) => {
    message.success(`登录成功！手机号：${values.phone}`)
    navigate('/')
  }

  return (
    <div style={{
      minHeight: '80vh',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      background: '#f0f2f5'
    }}>
      <Card title="手机号登录" style={{ width: 350 }} bordered={false}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号!' },
              { pattern: PHONE_REGEX, message: '请输入有效的手机号!' }
            ]}
          >
            <Input placeholder="手机号" size="large" maxLength={11} />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入验证码!' }]}
          >
            <Input
              placeholder="验证码"
              size="large"
              maxLength={6}
              addonAfter={
                <Button
                  style={{ padding: 0 }}
                  type="link"
                  disabled={countdown > 0}
                  onClick={handleGetCode}
                >
                  {countdown > 0 ? `${countdown}s后重试` : '获取验证码'}
                </Button>
              }
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
